import styled from "./chart.module.scss";
import { FC, useEffect, useRef } from "react";
import { init, type EChartsOption, type EChartsType } from "echarts";

interface ChartProps {
  title: string;
  width?: number;
  height?: number;
  option?: EChartsOption;
}

const Chart: FC<ChartProps> = ({ title, option, height = 400 }) => {
  const box = useRef<HTMLDivElement>(null);
  const ins = useRef<EChartsType>();

  // 图表初始化
  const initChart = () => {
    ins.current = init(box.current!, "", {
      height,
    });
  };

  useEffect(() => {
    if (!ins.current) {
      initChart();
    }

    option && ins.current?.setOption(option);
  }, [option]);

  useEffect(() => {
    // 监听 window.onresize 事件，来改变 图表实例
    function onResize() {
      ins.current && ins.current?.resize();
    }
    window.addEventListener("resize", onResize);

    return () => {
      window.removeEventListener("resize", onResize);
    };
  }, []);

  return (
    <div className={styled.box}>
      <div className={styled.top}>{title}</div>
      <div ref={box} className={styled.body}>
        {/* 图表 */}
      </div>
    </div>
  );
};

export default Chart;
